import requests
import json


def post_json(url, data, headers=None, timeout=10):
    """
    发送 JSON 格式的 POST 请求

    参数:
    url: 目标URL (字符串)
    data: 要发送的 JSON 数据 (字典)
    headers: 自定义请求头 (字典, 可选)
    timeout: 请求超时时间 (秒, 默认10秒)

    返回:
    Response 对象
    """
    # 设置默认请求头
    default_headers = {'Content-Type': 'application/json'}

    # 合并自定义请求头
    if headers:
        final_headers = {**default_headers, **headers}
    else:
        final_headers = default_headers

    try:
        # 发送 POST 请求
        response = requests.post(
            url,
            data=json.dumps(data),  # 将字典转换为 JSON 字符串
            headers=final_headers,
            timeout=timeout
        )
        return response

    except requests.exceptions.RequestException as e:
        # 处理请求异常
        print(f"请求失败: {e}")
        raise


# 使用示例
if __name__ == "__main__":
    # 目标 API 地址
    api_url = "https://api.example.com/endpoint"

    # 准备 JSON 数据
    payload = {
        "name": "John Doe",
        "email": "john@example.com",
        "age": 30,
        "interests": ["python", "api", "development"]
    }

    # 可选的额外请求头
    custom_headers = {
        "Authorization": "Bearer YOUR_ACCESS_TOKEN",
        "User-Agent": "MyApp/1.0"
    }

    try:
        # 发送请求
        response = post_json(api_url, payload, headers=custom_headers)

        # 输出响应结果
        print(f"状态码: {response.status_code}")
        print("响应内容:")
        print(response.json())  # 如果响应是 JSON 格式

    except Exception as e:
        print(f"程序出错: {e}")